<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>添加商品</title>
  <link rel="stylesheet" href="/static/layui/css/layui.css">
  <link rel="stylesheet" href="/static/admin/css/admin.css">
  <script src="/static/layui/layui.js"></script>
</head>
<body>
<div class="layui-container layui-p-30">  
  <form class="layui-form">
      
      <div class="layui-form-item">
        <label class="layui-form-label">排序</label>
        <div class="layui-input-inline">
          <input type="number" name="sort" value="0" lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
          <label class="layui-form-label">选择分类</label>
          <div class="layui-input-block">
            <select name="category_id" lay-verify="required" lay-search>
              <option value="">请选择分类</option>
              {foreach $options as $vo}
              <option value="{$vo.id}">{$vo.name}</option>
              {/foreach}
            </select>
          </div>
        </div>
      <div class="layui-form-item">
          <label class="layui-form-label">商品名称</label>
          <div class="layui-input-block">
            <input type="text" name="goods_name" required  lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
          </div>
        </div>
      <div class="layui-form-item">
        <label class="layui-form-label">商品图片</label>
        <div class="layui-input-block">
          <table class="layui-table" id="images">
              <tr>
                  <th width="90px">商品主图</th>
                  <th>商品轮播图</th>
              </tr>
              <tr>
                  <td>
                    <img src="/static/admin/img/upimg.png" class="layui-upimg" id="main-image">
                    <input type="hidden" name="main_image" id="main_image">
                  </td>
                  <td>
                    <div class="layui-inline">
                      <img src="/static/admin/img/upimg.png" class="layui-upimg" id="goods-images">
                    </div>
                  </td>
              </tr>
          </table>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">是否赠送积分</label>
        <div class="layui-input-block">
          <input type="radio" name="integral" value="1"  checked title="是">
          <input type="radio" name="integral" value="0" title="否">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">商品规格</label>
        <input type="hidden" name="goods_attr" id="attrs">
        <input type="hidden" name="skus" id="skus">
        <div class="layui-input-block">
              <div class="layui-inline">
                  <a class="layui-btn" id="group-add">添加分组</a>
              </div>
              <div id="group">
                  <div class="group-item">
                      <div class="group-parent">
                        <div class="layui-inline">
                          <input type="text" class="layui-input group_key" value="默认分组" />
                        </div>
                        <div class="layui-inline">
                          <a class="layui-btn layui-btn-normal group-add">添加规格</a>
                        </div>
                        <div class="layui-inline">
                          <a class="layui-btn layui-btn-danger group-del">删除分组</a>
                        </div>
                      </div>
                      <div class="group-son">
                        <div class="layui-inline group-son-item">
                          <div class="layui-inline">
                            <input type="text" lay-verify="required" class="layui-input group_val" value="默认规格" />
                          </div>
                          <div class="layui-inline">
                            <a class="layui-btn layui-btn-danger group-item-del">删除</a>
                          </div>
                        </div>
                      </div>
                  </div>
              </div>
                <table class="layui-table" id="group-table">
                    <tr>
                      <th>默认分组</th>
                      <th>图片</th>
                      <th>市场价</th>
                      <th>售卖价</th>
                      <th>库存</th>
                    </tr> 
                    <tr>
                      <td>默认规格</td>
                      <td>
                        <input type="hidden" class="image">
                        <img src="/static/admin/img/upimg.png"  class="layui-upimg sku-image">
                      </td>
                      <td><input type="number" attr-type="1" class="layui-input market_price" value="0.00"></td>
                      <td><input type="number" attr-type="1" class="layui-input sell_price" value="0.00"></td>
                      <td><input type="number" attr-type="2" class="layui-input stock" value="0"></td>
                    </tr>
              </table> 
           </div>   
      </div>
      <div class="layui-form-item">
          <label class="layui-form-label">商品详情</label>
          <div class="layui-input-block">
            <textarea name="content" id="content" style="display: none;" lay-verify="content"></textarea>
          </div>
        </div>
      <div class="layui-form-item">
        <label class="layui-form-label">是否上架</label>
        <div class="layui-input-block">
          <input type="radio" name="status" value="1"  checked title="上架">
          <input type="radio" name="status" value="0" title="下架">
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn" lay-submit lay-filter="formGoods">立即提交</button>
          <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
      </div>
    </form>
</div>  
<script>
    //Demo
    layui.use(['form','upload','layedit'], function(){
      var $ = layui.jquery,form = layui.form,upload = layui.upload,layedit = layui.layedit;
      upload.render({
          elem: "#main-image",
          accept: 'images',
          field: "image",
          url: "/admin/upload",
          done: function(res){
              if(res.code==1){
                let that = this.item;
                that.attr('src',res.src)
                $('#main_image').val(res.src);
              }
          }
      });

      upload.render({
          elem: "#goods-images",
          accept: 'images',
          field: "image",
          url: "/admin/upload",
          multiple: true,
          number:6,
          done: function(res){
              if(res.code==1){
                let that = this.item;
                let imgTpl = '<div class="layui-inline">' +
                    '<img src="'+res.src+'" class="layui-mul-upimg">' +
                    '<input type="hidden" name="goods_images[]" value="'+res.src+'">' +
                    '<i class="layui-icon layui-upimg-close">&#x1006</i>' +
                    '</div>';
                that.parent('div').before(imgTpl);
              }
          }
      });
      $('#images').on('click','.layui-upimg-close',function(){
            $(this).parents('.layui-inline').remove();
      });  
     
     layedit.set({
          uploadImage: {
             url: '/admin/upload/layedit', //接口url
             accept: 'images'
          }
      });

      let index =  layedit.build('content',{
        tool: ['center','left','right','image','strong', 'italic', 'underline', '|', 'del', 'link','unlink']
      });

      form.verify({
        content: function(value){
          return layedit.sync(index);
        }
      })

      let group_item = '<div class="group-item">' +
                    '<div class="group-parent">' +
                      '<div class="layui-inline">' +
                        '<input type="text" class="layui-input group_key" value="默认分组">' +
                      '</div>' +
                      '<div class="layui-inline">' +
                        '<a class="layui-btn layui-btn-normal group-add">添加规格</a>' +
                      '</div>' +
                      '<div class="layui-inline">'+
                        '<a class="layui-btn layui-btn-danger group-del">删除分组</a>' +
                      '</div>'+
                    '</div>' +
                    '<div class="group-son">' +
                      '<div class="layui-inline group-son-item">' +
                        '<div class="layui-inline">' +
                          '<input type="text" class="layui-input group_val" value="默认规格">' +
                        '</div>' +
                        '<div class="layui-inline">' +
                          '<a class="layui-btn layui-btn-danger del">删除</a>' +
                        '</div>' +
                      '</div>' +
                    '</div>'+
                '</div>';

      let group_son_item = '<div class="layui-inline group-son-item">' +
                              '<div class="layui-inline">' +
                                '<input type="text" class="layui-input group_val" value="默认规格">' +
                              '</div>' +
                              '<div class="layui-inline">' +
                                '<a class="layui-btn layui-btn-danger del">删除</a>' +
                              '</div>' +
                            '</div>';

      $('#group-add').click(function(){
            $('#group').append(group_item);
            generateTable();
      });

      $('#group').on('click','.group-del',function(){
            let len = $('.group-item').length
            if(len<2){
              layer.msg('最少设置一组分组',{icon:2})
              return false;
            }
            $(this).parents('.group-item').remove();
            generateTable();
      });

      $('#group').on('blur','.layui-input',function(){
         generateTable();
      });


      function getSkuData()
      {   
          let skuData = [];
          $('#group-table tr:not(:eq(0))').each(function(){
               let sku = {};
               let attr = '';
               $(this).find('.attr').each(function(){
                    attr+= $(this).text()+';';
               }); 
               sku.attr = attr;
               sku.image = $(this).find('.image').val();
               sku.market_price = $(this).find('.market_price').val();
               sku.sell_price = $(this).find('.sell_price').val();
               sku.stock = $(this).find('.stock').val();
               skuData.push(sku);
          });

          return skuData;
      }

      $('#group-table').on('blur','.layui-input',function(){
          let type = $(this).attr('attr-type');
          let val = $(this).val();
            if(type==1){
                if(val<0){
                  $(this).val(0);
                  layer.msg('无效的价格输入',{icon:2})
                }
                return false;
            }

            if(type==2){
              if(val<0){
                  $(this).val(0);
                  layer.msg('无效的库存值',{icon:2})
                }
            }
      });


      $('#group').on('click','.group-add',function(){
          $(this).parents('.group-parent').siblings('.group-son').append(group_son_item);
          generateTable();
      });

      $('#group').on('click','.del',function(){
          let len = $(this).parents('.group-son').find('.group-son-item').length;
          if(len<2){
              layer.msg('最少设置一项规格',{icon:2})
              return false;
            }
          $(this).parents('.group-son-item').remove();
          generateTable();
      });

      function cartesianProductOf() {
          return Array.prototype.reduce.call(arguments,function(a, b) {
              var ret = [];
              a.forEach(function(a) {
                  b.forEach(function(b) {
                      ret.push(a.concat([b]));
                  });
              });
              return ret;
          }, [[]]);
      }
      

      function generateTable(){
          let keys = [];
          let vals = [];
          let attrs = [];
          let skus = [];
          let thead = '';
          let tbody = '';
          $('.group-item').each(function(){
               let key = $(this).find('.group_key').val();
               let val = [];
               keys.push(key);
                $(this).find('.group_val').each(function(){
                  val.push($(this).val());
               });
               vals.push(val);
               attrs.push({[key]:val});
          });
          $('#attrs').val(JSON.stringify(attrs));
          thead += '<tr>';
          keys.forEach(function(item){
             thead += '<th>';
             thead += item;
             thead += '</th>';
          });
          thead += '<th>图片</th>' +
                   '<th>市场价</th>' +
                   '<th>售卖价</th>' +
                    '<th>库存</th>';
          thead += '</tr>';
          
          skus = cartesianProductOf(...vals);
          
          tbody = '';
          skus.forEach((vals) => {
              tbody += '<tr>';
              vals.forEach((v) => {
                tbody += '<td class="attr">';
                tbody += v;  
                tbody += '</td>';  
              });
              tbody += '<td>' +
                   '<img src="/static/admin/img/upimg.png"  class="layui-upimg sku-image"></td>' +
                   '<td><input type="number" attr-type="1" class="layui-input market_price" value="0.00"></td>' +
                   '<td><input type="number" attr-type="1" class="layui-input sell_price" value="0.00"></td>' +
                   '<td><input type="number" attr-type="2" class="layui-input stock" value="0"></td>';
              tbody += '</tr>';
          });
          
          let html = thead+tbody
          
          $('#group-table').html(html);


          upload.render({
            elem: '.sku-image',
            accept: 'images',
            field: "image",
            url: "/admin/upload",
            done: function(res){
                if(res.code==1){
                  let that = this.item
                   that.attr('src',res.src)
                   that.append('<input type="hidden" class="image" value="'+res.src+'">');
                }
            }
         });
      }

      form.on('submit(formGoods)',function(data){
          data.field.skus = getSkuData();
          console.log(data.field);
          $.post('/admin/goods/save',data.field,function(res){
                  if(res.code ==1 ){
                    let index =  parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    parent.$.pjax({container: '#main',fragment: '#main'}).reload;
                    return false;
                  }

                  return layer.msg(res.msg,{icon:2});
          }); 

          return false;
      });

    
  });
</script>
</body>
</html>